<!-- 添加试题模板 -->
<script lang="ts">
export declare interface ruleFormType {
  type: number;
  opsType: number;
  ownerType: number;
  options: Array<{
    optionId: string;
    optionText: string;
    isAnswer: number;
    answerText: string;
  }>;
  singleAnswer?: string;
  multipleAnswer?: string[];
  [propName: string]: any;
}
</script>
<script setup lang='ts'>
import { reactive, ref, toRaw } from 'vue';
import { SubjectType } from './batchUpload.vue'
import { ResponseType } from '@/common/types/response';
import { useCurrentInstance } from '@/common/utils/methods'
import type { ElForm } from 'element-plus'

type FormInstance = InstanceType<typeof ElForm>
const { $confirm, $message, $axios, branchId, brandId, branchType } = useCurrentInstance();

const props = defineProps<{
  subjectList: Array<SubjectType>
}>()

const emit = defineEmits<{
  (e: 'updateList'): void
  (e: 'preview', previewInfo: ruleFormType): void
}>()

const data = reactive({
  dialogVisible: false,
  dialogTitle: '',
})

const ruleFormRef = ref<FormInstance>()
let ruleForm: ruleFormType = reactive({
  analysisText: '', // 解析
  branchId,
  brandId,
  opsType: 1,
  options: [],
  ownerType: 1, // 
  questionId: '', // 问题ID
  stemText: '', // 题干
  subjectId: '', // 科目ID
  type: 1, // 题型
  singleAnswer: '', // 单选或判断答案
  multipleAnswer: [], // 多选答案
})

const rules = reactive({
  subjectId: [
    {
      required: true,
      message: '请选择题目',
      trigger: 'blur',
    },
  ],
  stemText: [
    {
      required: true,
      message: '请输入题干',
      trigger: 'blur'
    }
  ]
})

const addOption = () => { // 添加选项
  ruleForm.options.push({
    optionId: '',
    optionText: '',
    isAnswer: 0,
    answerText: '',
  })
}

// 移除选项
const removeOption = (index: number) => { // 移除选项
  ruleForm.options.splice(index, 1)
}

// 编号 转 大写字母
const numToLetter = (num: number) => { // 数字转英文字母
  return String.fromCharCode(64 + num)
}

const formatRuleForm = (): ruleFormType => {
  let formatForm = toRaw(ruleForm);
  if (formatForm.type === 1) {
    const answerIndex = formatForm.singleAnswer && formatForm.singleAnswer.charCodeAt(0) - 65;
    formatForm.options = formatForm.options.map((item, index) => {
      item.isAnswer = index === answerIndex ? 1 : 0;
      return item;
    })
  } else if (formatForm.type === 2) {
    if (formatForm.multipleAnswer) {
      const asnwerMap = formatForm.multipleAnswer.map((item) => (('' + item).charCodeAt(0) - 65))
      formatForm.options = formatForm.options.map((item, index) => {
        item.isAnswer = asnwerMap.indexOf(index) > -1 ? 1 : 0;
        return item;
      })
    }
  } else if (formatForm.type === 3) {
    const isRight = formatForm.singleAnswer === '正确';
    formatForm.options = [
      { optionId: "", optionText: "正确", isAnswer: isRight ? 1 : 0, answerText: "" },
      { optionId: "", optionText: "错误", isAnswer: isRight ? 0 : 1, answerText: "" }
    ]
  }
  return formatForm;
}

const beforeClose = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      saveQuestion(() => {
        data.dialogVisible = false;
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  ruleForm.singleAnswer = '';
  ruleForm.multipleAnswer = [];
  ruleForm.analysisText = '';
  formEl.resetFields()
}

// 保存试题
const saveQuestion = (callback?: ()=>void) => {
  const params = formatRuleForm()
  $axios.post('/training.exam.api/question/create', params).then((res: ResponseType) => {
    if (res.code === '200') {
      const questionSaveType = params.opsType === 2 ? '编辑':'新增';
      const questionType = ['', '单选', '多选', '判断'][params.type]
      $message.success(questionSaveType + questionType +'成功');

      // 重置表单
      resetForm(ruleFormRef.value);

      // 保存试题后，更新试题列表
      emit('updateList');

      // 非公共逻辑走callback
      typeof callback === 'function' && callback()
    }
  })
}

// 试题预览
const showPreview = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, err) => {
    if (valid) {
      const formatForm = formatRuleForm()
      emit('preview', formatForm)
    }
  })
}

const addNextQuestion = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid, err) => {
    if (valid) {
      saveQuestion()  
    }
  })
}

// 设置题目信息
const setQuestionInfo = (questionInfo: ruleFormType) => {
  for (let key in questionInfo) {
    if (questionInfo[key] && key.indexOf('_') === -1) {
      ruleForm[key] = questionInfo[key]
    }
  }
  const isAdd = questionInfo._actionType === 'add';
  ruleForm.opsType = isAdd ? 1 : 2;
  data.dialogTitle = (isAdd ? '新增' : '编辑') + ['单选', '多选', '判断'][questionInfo._type - 1];
  if (isAdd) { // 如果是添加，则选项至少是两个
    addOption();
  } else {
    // 编辑时，对选项特殊处理
    ruleForm.multipleAnswer = [];
    ruleForm.singleAnswer = '';
    questionInfo.options.forEach((item, index) => {
      if (item.isAnswer === 1) {
        if (questionInfo._type === 1) {
          ruleForm.singleAnswer = numToLetter(index+1)
        } else if (questionInfo._type === 2) {
          Array.isArray(ruleForm.multipleAnswer) && ruleForm.multipleAnswer.push(numToLetter(index+1))
        } else {
          ruleForm.singleAnswer = item.optionText;
        }
      }
    })
  }
  data.dialogVisible = true;
}

defineExpose({
  setQuestionInfo
})
</script>

<template>
  <el-dialog 
    v-model="data.dialogVisible" 
    :title="data.dialogTitle" 
    width="850px" 
    :before-close="beforeClose"
  >
    <el-form 
      ref="ruleFormRef" 
      :model="ruleForm" 
      :rules="rules" 
      label-width="80px"
    >
      <el-form-item label="科目" prop="subjectId">
        <el-select v-model="ruleForm.subjectId" placeholder="请选择科目">
          <el-option
            :label="subject.label"
            :value="subject.value"
            v-for="subject in subjectList"
            :key="subject.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题干" prop="stemText">
        <el-input
          class="limitWidth"
          v-model="ruleForm.stemText"
          maxlength="256"
          placeholder="请输入题干"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
      <template v-if="ruleForm.type !== 3">
        <el-form-item
          :label="'选项' + numToLetter(index + 1)"
          :prop="'options.' + index + '.optionText'"
          v-for="(option, index) in ruleForm.options"
          :key="index"
          :rules="[
            {
              required: true,
              message: '请输入内容',
              trigger: 'blur',
            }
          ]"
        >
          <el-input
            class="limitWidth"
            v-model="option.optionText"
            placeholder="请输入内容"
            type="textarea"
          />
          <el-button
            type="success"
            circle
            class="answerAction"
            @click="addOption"
            v-if="index === 0"
          >
            <el-icon>
              <plus />
            </el-icon>
          </el-button>
          <el-button
            style="background:#f56c6c"
            circle
            class="answerAction"
            @click="removeOption(index)"
            v-else
          >
            <el-icon color="#fff">
              <minus />
            </el-icon>
          </el-button>
        </el-form-item>
      </template>

      <template v-if="[1, 3].includes(ruleForm.type)">
        <el-form-item
          ref="singleAnswer"
          label="正确选项"
          prop="singleAnswer"
          :rules="[
            {
              required: true,
              message: '请选择答案',
              trigger: 'blur',
            },
          ]"
        >
          <el-radio-group v-model="ruleForm.singleAnswer" v-if="ruleForm.type === 1">
            <el-radio
              :label="numToLetter(e)"
              v-for="(e, index) in ruleForm.options.length"
              :key="e"
            ></el-radio>
          </el-radio-group>

          <el-radio-group v-model="ruleForm.singleAnswer" v-if="ruleForm.type === 3">
            <el-radio label="正确"></el-radio>
            <el-radio label="错误"></el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item
          ref="mutipleAnswer"
          label="正确选项"
          prop="multipleAnswer"
          :rules="[
            {
              required: true,
              message: '请选择答案',
              trigger: 'blur',
            },
          ]"
        >
          <el-checkbox-group v-model="ruleForm.multipleAnswer">
            <el-checkbox
              :label="numToLetter(e)"
              name="type"
              v-for="e in ruleForm.options.length"
              :key="e"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </template>

      <el-form-item label="解析">
        <el-input
          class="limitWidth"
          v-model="ruleForm.analysisText"
          maxlength="256"
          placeholder="请输入解析"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="submitForm(ruleFormRef)">确定</el-button>
        <el-button type="primary" @click="showPreview(ruleFormRef)">预览</el-button>
        <el-button type="primary" @click="addNextQuestion(ruleFormRef)">新增下一题</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.limitWidth {
  width: calc(100% - 42px);
}
.answerAction {
  margin-left: 10px;
}
</style>